package com.wxw.gulidemo.controller;

import com.alibaba.druid.sql.transform.SQLUnifiedUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wxw.gulidemo.R;
import com.wxw.gulidemo.client.ServiceEduClient;
import com.wxw.gulidemo.client.ServiceUcenterClient;
import com.wxw.gulidemo.entity.Order;
import com.wxw.gulidemo.service.IOrderService;
import com.wxw.gulidemo.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author xinxinzi
 * @since 2022-06-20
 */
@RestController
@CrossOrigin
@RequestMapping("/eduOrder/t-order")
public class OrderController {

    @Autowired
    private IOrderService orderService;

    //生成订单
    @PostMapping("/createOrder/{courseId}")
    public R createOrder(@PathVariable String courseId,
                         HttpServletRequest request){
        //从请求头中获取用户id
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        //判断是否登录
        if (StringUtils.isEmpty(memberId)){
            throw new NullPointerException();
        }

        //生成订单，并生成对应的订单号
        String orderNo = orderService.createOrders(courseId,memberId);

        return R.ok().data("orderNo",orderNo);
    }

    //根据订单号查询订单信息
    @GetMapping("/getOrderInfoById/{orderNo}")
    public R getOrderInfoById(@PathVariable String orderNo){
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderNo);
        Order order = orderService.getOne(wrapper);
        return R.ok().data("item",order);
    }

    //根据【用户id、课程id】查询订单表中的状态 --- 1为已支付
    @PostMapping("/isBuyCourse/{memberId}/{courseId}")
    public boolean isBuyCourse(@PathVariable String memberId,
                         @PathVariable String courseId){
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("member_id",memberId);
        queryWrapper.eq("course_id",courseId);
        queryWrapper.eq("status",1);
        long count = orderService.count(queryWrapper);
        if (count > 0) {
            return true;
        }
        return false;
    }

}
